package com.yilin.tms.message.service.impl;

import com.yilin.commons.util.DateTimeUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.entity.message.MessageData;
import com.yilin.tms.message.repository.MessageDataRepository;
import com.yilin.tms.message.service.IMessageService;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 聊天记录服务
 *
 * @author zhangjinyuan
 * @date 2022/10/26
 */
@Service
@Transactional
public class MessageService implements IMessageService {

    @Resource
    MessageDataRepository messageDataRepository;

    /**
     * 聊天记录分页查询
     */
    @Override
    public PageData<MessageData> getChatPage(MessageData query, Integer start, Integer limit) {
        Pageable pageable = PageRequest.of(start - 1, limit);
        Example<MessageData> stExample = Example.of(query);
        Page<MessageData> all = messageDataRepository.findAll(stExample, pageable);
        PageData<MessageData> pageData = new PageData<>();
        pageData.setList(all.getContent());
        pageData.setTotal(all.getTotalElements());
        return pageData;
    }

    /**
     * 保存和更新聊天记录
     */
    @Override
    public void saveOrUpdate(MessageData messageData) {
        messageDataRepository.save(messageData);
    }

    /**
     * 根据发送日期删除消息记录
     */
    @Override
    public void deleteByDate(String startDate, String endDate) {
        List<MessageData> list = messageDataRepository.findBySendTimeBetween(
                DateTimeUtil.stringToDate(startDate, "yyyy-MM-dd HH:mm:ss"),
                DateTimeUtil.stringToDate(endDate, "yyyy-MM-dd HH:mm:ss"));
        messageDataRepository.deleteAll(list);
    }

    /**
     * 根据id数组删除数据
     */
    @Override
    public void deleteByIds(String[] ids) {
        for (String id : ids) {
            messageDataRepository.deleteById(id);
        }
    }

    /**
     * MONGO_DB
     * 根据收件人获取未读信息
     */
    @Override
    public List<MessageData> getFailChatListByReceiveUserId(String receiveUserId) {
        MessageData messageData = new MessageData();
        messageData.setToAccountId(receiveUserId);
        messageData.setSendState(MessageData.SendState.fail);
        Example<MessageData> stExample = Example.of(messageData);
        return messageDataRepository.findAll(stExample);
    }


}
